﻿using Caliburn.Micro;
using HalconDotNet;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace HalconTest
{
    public class ShellViewModel : PropertyChangedBase
    {
        HImage image;
        HDrawingObject shape;
        HTuple hv_ModleID = new HTuple();

        HSmartWindowControlWPF smartWindow { get; set; }
        List<HDrawingObjectModel> drawingObjects = new List<HDrawingObjectModel> ();


        private string _title;
        public string Title
        {
            get => _title;
            set
            {
                _title = value;
                NotifyOfPropertyChange("Title");
            }
        }

        private string _result;

        public string Result
        {
            get { return _result; }
            set { Set(ref _result, value); }
        }


        public ShellViewModel()
        {
            Title = "Welcome to Caliburn Micro in .net 6 WPF";
        }
        public void LoadImage(object obj)
        {
            smartWindow = ((ShellView)obj).hWindowControlWPF;
            //DisplayImage();
            OpenImage();
        }
        private void DisplayImage()
        {
            string path = @"E:\dog.png";
            image = new HImage(path);
            HWindow window = smartWindow.HalconWindow;
            window.DispObj(image);
            smartWindow.SetFullImagePart(image);

            //画region
            //window.SetColor("red");
            //window.SetDraw("margin");
            //HRegion region = new HRegion();
            //region.GenRectangle1((HTuple)10, 10, 100, 100);
            //region.DispRegion(window);

            //画圆
            //HObject circle;
            //HOperatorSet.GenCircle(out circle, 300, 300, 100);
            //window.SetColor("green");
            //window.SetDraw("fill");
            //window.DispObj(circle);

        }

        public void CreateModel()
        {
            HObject ho_circle;
            HObject ho_ImageReduced;
            
            var tuples = drawingObjects.ElementAt(0).HTuples;
            HOperatorSet.GenCircle(out ho_circle, tuples[0], tuples[1], tuples[2]);
            HOperatorSet.ReduceDomain(image, ho_circle, out ho_ImageReduced);
            HOperatorSet.CreateScaledShapeModel(ho_ImageReduced, "auto", -0.39, 0.79, "auto", 0.9, 1.1, "auto", "auto", "use_polarity", "auto", "auto", out hv_ModleID);

            string fileName = AppDomain.CurrentDomain.BaseDirectory + "Model.shm";
            HOperatorSet.WriteShapeModel(hv_ModleID, fileName);

            // 将'drawingObject'对象的可见性设置为false来隐藏它
            //shape.SetDrawingObjectParams("visible", "false");
            // 从'smartWindow.HalconWindow'中分离'drawingObject'对象，这将导致对象不再显示
            smartWindow.HalconWindow.DetachDrawingObjectFromWindow(shape);

        }

        public void Match()
        {
            var results = Execute(smartWindow.HalconWindow, image, hv_ModleID);
            foreach (var item in results)
            {
                Result += $"Row:{item.Row} Column:{item.Column} Radius:{item.Radius} \r\n";
            }
        }

        private List<Result> Execute(HTuple hv_WindowHandle, HObject ho_GrayImage, HTuple hv_ModelID)
        {
            List<Result> results = new List<Result>();

            HTuple hv_Row1 = new HTuple(), hv_Column1 = new HTuple();
            HTuple hv_Angle = new HTuple(), hv_Scale = new HTuple(), hv_Score = new HTuple();
            try
            {
                hv_Row1.Dispose(); hv_Column1.Dispose(); hv_Angle.Dispose(); hv_Scale.Dispose(); hv_Score.Dispose();

                //万国型号对位的结果， ho_GrayImage 对象  视点 hv_ModelID
                HOperatorSet.FindScaledShapeModel(ho_GrayImage, hv_ModelID, -0.39, 0.78, 0.9,
                    1.1, 0.85, 0, 0.5, "least_squares", 0, 0.9, out hv_Row1, out hv_Column1,
                    out hv_Angle, out hv_Scale, out hv_Score);
                HOperatorSet.DispCross(hv_WindowHandle, hv_Row1, hv_Column1, 16, 0);

                if (hv_Score.Length > 0)
                {
                    for (int i = 0; i < hv_Score.Length; i++)
                    {
                        results.Add(new Result
                        {
                            Row = hv_Row1.DArr[i],
                            Column = hv_Column1.DArr[i],
                            Radius = hv_Score.DArr[i],
                        });
                    }
                }

            }
            catch { }

            return results;
        }

        public void LoadModel()
        {
            string fileName = AppDomain.CurrentDomain.BaseDirectory + "Model.shm";
            HOperatorSet.ReadShapeModel(fileName,out hv_ModleID);
        }

        public void CreateShape()
        {
            var drawingParam = new HTuple[] { 100, 100, 50 };
            shape = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE, drawingParam);
            smartWindow.HalconWindow.AttachDrawingObjectToWindow(shape);
            drawingObjects.Add(new HDrawingObjectModel
            {
                DrawingObject = shape,
                HTuples = drawingParam
            });

            shape.OnDrag(HDrawingObjectCallback);
            shape.OnResize(HResizeCallback);
        }
        public void HResizeCallback(HDrawingObject drawid, HWindow window, string type)
        {
            GetParams(drawid);
        }
        public void HDrawingObjectCallback(HDrawingObject drawid, HWindow window, string type)
        {
            GetParams(drawid);
        }
        void GetParams(HDrawingObject drawid)
        {
            var tuples = new HTuple[3];
            tuples[0] = drawid.GetDrawingObjectParams("row");
            tuples[1] = drawid.GetDrawingObjectParams("column");
            tuples[2] = drawid.GetDrawingObjectParams("radius");

            var drawObj = drawingObjects.FirstOrDefault(o => o.DrawingObject.ID.Equals(drawid.ID));
            if (drawObj != null)
            {
                drawObj.HTuples = tuples;
            }

            Debug.WriteLine($"rows:{tuples[0]} columns:{tuples[1]} radius:{tuples[2]}");
        }
        void OpenImage()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog(); //打开文件进行选择
            openFileDialog.Filter = "所有支持的图像格式|*.jpg;*.jpeg;*.png|JPEG 图像|*.jpg;*.jpeg|PNG 图像|*.png|位图图像|*.bmp";
            if (openFileDialog.ShowDialog() == true)
            {
                string path = openFileDialog.FileName;
                image = new HImage(path);
                HWindow window = smartWindow.HalconWindow;
                window.DispObj(image);
                smartWindow.SetFullImagePart();
            }
        }

    }

    public class HDrawingObjectModel
    { 
        public HTuple[] HTuples { get; set; }
        public  HDrawingObject DrawingObject { get; set; }

    }

    public class Result 
    {
        public double Row { get; set; }
        public double Column { get; set; }
        public double Radius { get; set; }
    }
}
